package com.zplus.managers.petservices.controllers;

import com.alibaba.fastjson2.JSON;
import com.zplus.managers.petservices.entities.User;
import com.zplus.managers.petservices.services.UserService;
import com.zplus.managers.petservices.utils.Message;
import com.zplus.managers.petservices.utils.Page;
import com.zplus.managers.petservices.utils.PagingFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController
{
    @Autowired
    private UserService userService;

    private PagingFactory pagingFactory;
    /**
     * get target user by it name
     * @param nickname the user nickname
     * @return message object, a map holds target user with code 200 if operation success,
     * empty map with code 100 otherwise
     */
    @RequestMapping(value = "/getbyname", method = RequestMethod.GET)
    @ResponseBody
    public Message getUserByName(@RequestParam("nickname") String nickname)
    {
        List<User> users = userService.queryUserByName(nickname);
        Message msg = new Message();
        msg.load(users);
        return msg;
    }

    /**
     * get all user in database
     * @return message object, a map of users with code 200 if operation success,
     * empty map with code 100 otherwise
     */
    @RequestMapping(value = "/getallusers", method = RequestMethod.GET)
    @ResponseBody
    public Message getAllUsers(@RequestParam("pageSize") int pageSize)
    {
        List<User> users = userService.queryAllUser();
        Message msg = new Message();
        if(users == null)
        {
            msg.fail();
            return msg;
        }

        pagingFactory = new PagingFactory(users, pageSize);
        Page page = pagingFactory.nextPage();
        msg.loadPage(page);
        return msg;
    }

    @RequestMapping(value = "/getuserbyid",method = RequestMethod.GET)
    @ResponseBody
    public Message getUserById(@RequestParam("uid")int uid)
    {
        Message msg = new Message();
        User user = userService.queryUserById(uid);
        if(user == null)
        {
            msg.fail();
            return msg;
        }
        List<User> ulst = new ArrayList<>();
        ulst.add(user);
        msg.load(ulst);
        return msg;
    }

    /**
     * update user info
     * valid user id needed
     * @param user target user
     * @return message object, code 200 if operation success, code 100 otherwise
     */
    @RequestMapping(value = "/updateuser", method = RequestMethod.POST)
    @ResponseBody
    public Message updateUserInfo(@RequestBody User user)
    {
        Message msg = new Message();
        if(userService.updateUserInfo(user))
            msg.ok();
        else
            msg.fail();

        return msg;
    }

    /**
     * delete a user by it id
     * @param id user id
     * @return message object, code 200 if operation success, code 100 otherwise
     */
    @RequestMapping(value = "/deluser", method = RequestMethod.GET)
    @ResponseBody
    public Message deleteUser(@RequestParam("uid") int id)
    {
        Message msg = new Message();
        User delUser = new User();
        delUser.setId(id);
        if( userService.delUser(delUser))
            msg.ok();
        else
            msg.fail();
        return msg;
    }

    /**
     * add User, accept user object
     * @param user user object
     * @return mssage object,code 200 if operation success, code 100 otherwise
     */
    @RequestMapping(value = "/newuser", method = RequestMethod.POST)
    @ResponseBody
    public Message addUser(@RequestBody User user)
    {
        Message msg = new Message();
        if (userService.register(user))
            msg.ok();
        else
            msg.fail();

        return msg;
    }
    
    /**
     * get page by specify a index
     * @param index the page index
     * @return Messgae with code 200 contains page data if success, code 100 and contains empty page otherwise
     */
    @RequestMapping("/getpage")
    @ResponseBody
    public Message getPage(@RequestParam("index") int index)
    {
        Message msg = new Message();
        if(pagingFactory == null)
        {
            msg.fail("paggingFactory not initialized");
            return msg;
        }

        Page page = pagingFactory.getPage(index);
        msg.loadPage(page);
        return msg;
    }


    /**
     * check user login.
     * fields required:
     *     "phoneNum", "secret"
     *
     * cookie contains fields:
     *     "user.name", "user.gender", "user.age",
     *     "user.phone", "user.addr", "user.email",
     *     "user.exp"
     *
     * @param usr account info
     * @param req handle by browser, ignore it
     * @param resp handle by server, igonre it
     * @return Message with code 100 and a cookie with logined user's info, code 200 with no cookie otherwise
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    Message checkLogin(@RequestBody User usr, HttpServletRequest req, HttpServletResponse resp)
    {
        Message msg = new Message();
        User user;

        user = userService.checkLogin(usr);
        if(user != null)
        {
            msg.ok();
            user.setSecret("");
            List<User> usrlist = new ArrayList<>();
            usrlist.add(user);
            msg.load(usrlist);
            String str = URLEncoder.encode(JSON.toJSONString(user), StandardCharsets.UTF_8);
            Cookie coo = new Cookie("userinfo",str);

            coo.setMaxAge(30);
            resp.addCookie(coo);
        }
        else
            msg.fail();
        return msg;
    }
}

